#include <iostream>
#include <cstring>
#include <sys/mman.h>
#include <dlfcn.h>
#include <stdint.h>

unsigned char code[] =
	"\x48\x89\xf8"   // mov rax, rdi
	"\x48\x01\xf0"   // add rax, rsi
	"\xc3";          // retq

typedef int (*func_ptr)(int, int);

int run_code(int a, int b) {
	void* memory = mmap(0, sizeof(code), PROT_EXEC | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
	if (memory == MAP_FAILED) {
		std::cerr << "Memory mapping failed." << std::endl;
		return -1;
	}

	std::memcpy(memory, code, sizeof(code));
	mprotect(memory, sizeof(code), PROT_EXEC | PROT_READ);

	func_ptr func = reinterpret_cast<func_ptr>(memory);
	int result = func(a, b);

	munmap(memory, sizeof(code));
	return result;
}

int main() {
	int result = run_code(1, 2);
	std::cout << "The result is: " << result << std::endl;
	return 0;
}
